
package com.aaa.boot.exception;

import com.aaa.boot.result.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局异常处理器（集中处理控制器层异常）
 * @author MK
 * @version 1.1
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理业务逻辑异常
     * @param e 业务异常实例，包含自定义错误码和提示信息
     * @return 标准错误响应(HTTP 200 + 业务错误码)
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public AjaxResult handleBusinessException(BusinessException e) {
        log.warn("业务异常[code={}]：{}", e.getCode(), e.getMessage());
        return new AjaxResult(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常（JSR-303规范）
     * @param e 参数校验异常实例
     * @return 参数错误响应(HTTP 400)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult handleValidException(MethodArgumentNotValidException e) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("timestamp", new Date());
        response.put("status", HttpStatus.BAD_REQUEST.value());
        List<String> errors = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.toList());

        response.put("errors", errors);
        log.warn("参数校验失败：{}", response);
        return new AjaxResult(301,new ResponseEntity<>(response, HttpStatus.BAD_REQUEST));
    }

    /**
     * 处理参数绑定异常（如类型转换错误）
     * @param e 参数绑定异常实例
     * @return 参数错误响应(HTTP 400)
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult handleBindException(BindException e) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("timestamp", new Date());
        response.put("status", HttpStatus.BAD_REQUEST.value());
        List<String> errors = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.toList());

        response.put("errors", errors);
        log.warn("参数绑定异常：{}", response);
        return new AjaxResult(400, new ResponseEntity<>(response, HttpStatus.BAD_REQUEST));
    }

    /**
     * 处理通用异常（兜底处理）
     * @param e 异常实例
     * @return 系统错误响应(HTTP 500)
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult handleException(Exception e) {
        log.error("系统异常：", e);
        e.printStackTrace();
        return new AjaxResult(500, "系统繁忙，请稍后重试");
    }
}
